<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%" max-height="60vh" scroll>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="基本信息" name="1">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="藏品总登记号" prop="generalAccessionNumber">
                <el-input
                  v-model="formData.generalAccessionNumber"
                  placeholder="请输入藏品总登记号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号类型" prop="numberType">
                <el-select v-model="formData.numberType" placeholder="请选择编号类型">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_NUM_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号" prop="number">
                <el-input v-model="formData.number" placeholder="请输入编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="原名" prop="originalName">
                <el-input v-model="formData.originalName" placeholder="请输入原名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年代" prop="era">
                <!-- chineseHistoricalEra,archaeologicalEra,geologicalEra,era -->
                <!-- eraList -->
                <!-- <el-input v-model="formData.era" placeholder="请输入年代" /> -->
                <el-cascader
                  v-model="formData.eras"
                  :options="eraList"
                  :props="{
                    ...defaultPropsTree,
                    disabled: (data) => data.status === 1
                  }"
                  filterable
                  placeholder="请选择年代"
                  style="width: 100%"
                  @change="onChangeEras"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="具体年代" prop="specificEra">
                <el-input v-model="formData.specificEra" placeholder="请输入具体年代" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文物类别" prop="category">
                <el-select v-model="formData.category" placeholder="请选择文物类别">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_CATEGORY)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- materialCategory1, materialCategory2, materialCategory3=material -->
              <el-form-item label="质地类别" prop="material">
                <el-cascader
                  v-model="formData.materialCategory3"
                  :options="cataList"
                  :props="{
                    ...defaultPropsTree,
                    disabled: (data) => data.status === 1
                  }"
                  filterable
                  placeholder="请选择质地类别"
                  style="width: 100%"
                  @change="onChangeMaterial"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="件数" prop="numberOfCases">
                <el-input v-model="formData.numberOfCases" placeholder="请输入件数" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="numberUnit">
                <el-select v-model="formData.numberUnit" placeholder="请选择单位">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_NUM_UNIT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际数量" prop="actualQuantity">
                <el-input v-model="formData.actualQuantity" placeholder="请输入实际数量" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="通长" prop="sizeLength">
                <el-input v-model="formData.sizeLength" placeholder="请输入外形尺寸(cm)-通长" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通宽" prop="sizeWidth">
                <el-input v-model="formData.sizeWidth" placeholder="请输入外形尺寸(cm)-通宽" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通高" prop="sizeHeight">
                <el-input v-model="formData.sizeHeight" placeholder="请输入外形尺寸(cm)-通高" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="具体尺寸" prop="specificSize">
                <el-input v-model="formData.specificSize" placeholder="请输入具体尺寸" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="质量范围" prop="weightRange">
                <el-input v-model="formData.weightRange" placeholder="请输入质量-质量范围" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="具体质量" prop="specificWeight">
                <el-input v-model="formData.specificWeight" placeholder="请输入质量-具体质量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="weightUnit">
                <el-select v-model="formData.weightUnit" placeholder="请选择质量-单位">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_QUALITY_UNIT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="文物级别" prop="relicLevel">
                <el-select v-model="formData.relicLevel" placeholder="请选择文物级别">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_GRADE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文物来源" prop="relicSource">
                <el-select v-model="formData.relicSource" placeholder="请选择文物来源">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_SOURCE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="完残程度" prop="completenessDegree">
                <el-select v-model="formData.completenessDegree" placeholder="请选择完残程度">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_CONDITION_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="完残状况" prop="completenessCondition">
                <el-input v-model="formData.completenessCondition" placeholder="请输入完残状况" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="保存状态" prop="preservationState">
                <el-select v-model="formData.preservationState" placeholder="请选择保存状态">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_PRESERVATION_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入藏时间范围" prop="collectionTimeRange">
                <el-input v-model="formData.collectionTimeRange" placeholder="请输入入藏时间范围" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入藏年度" prop="collectionYear">
                <el-input v-model="formData.collectionYear" placeholder="请输入入藏年度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="藏品登记号" prop="collectionRegistrationNumber">
                <el-input
                  v-model="formData.collectionRegistrationNumber"
                  placeholder="请输入藏品登记号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本" prop="version">
                <el-input v-model="formData.version" placeholder="请输入版本" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存卷" prop="storageVolume">
                <el-input v-model="formData.storageVolume" placeholder="请输入存卷" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行政区划" prop="administrativeDivision">
                <el-input v-model="formData.administrativeDivision" placeholder="请输入行政区划" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位编码" prop="unitCode">
                <el-input v-model="formData.unitCode" placeholder="请输入单位编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位名称" prop="unitName">
                <el-input v-model="formData.unitName" placeholder="请输入单位名称" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="扩展信息" name="2" v-if="['10', '13'].includes(formData.category)">
          <!--      书画类藏品特有字段-->
          <el-row :gutter="20" v-if="formData.category === '10'">
            <el-col :span="8">
              <el-form-item label="画心尺寸-长" prop="paintingLength">
                <el-input v-model="formData.paintingLength" placeholder="请输入画心尺寸-长">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="宽" prop="paintingWidth">
                <el-input v-model="formData.paintingWidth" placeholder="请输入画心尺寸-宽">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="高" prop="paintingHeight">
                <el-input v-model="formData.paintingHeight" placeholder="请输入画心尺寸-高">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="装裱尺寸-长" prop="mountingLength">
                <el-input v-model="formData.mountingLength" placeholder="请输入装裱尺寸-长">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="宽" prop="mountingWidth">
                <el-input v-model="formData.mountingWidth" placeholder="请输入装裱尺寸-宽">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="高" prop="mountingHeight">
                <el-input v-model="formData.mountingHeight" placeholder="请输入装裱尺寸-高">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容题材" prop="subjectMatter">
                <el-input v-model="formData.subjectMatter" placeholder="请输入内容题材" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="技法风格" prop="techniqueStyle">
                <el-input v-model="formData.techniqueStyle" placeholder="请输入技法风格" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="款识信息" prop="inscriptionInfo">
                <el-input v-model="formData.inscriptionInfo" placeholder="请输入款识信息" />
              </el-form-item>
            </el-col>
          </el-row>

          <!--      印章类藏品特有字段-->
          <el-row :gutter="20" v-else>
            <el-col :span="12">
              <el-form-item label="形状" prop="shape">
                <el-input v-model="formData.shape" placeholder="请输入形状" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="钮式" prop="knobStyle">
                <el-input v-model="formData.knobStyle" placeholder="请输入钮式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文字类型" prop="textType">
                <el-select v-model="formData.textType" placeholder="请选择文字类型">
                  <el-option label="请选择字典生成" value="" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="边框特征" prop="borderFeature">
                <el-input v-model="formData.borderFeature" placeholder="请输入边框特征" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="印面尺寸" prop="sealSize">
                <el-input v-model="formData.sealSize" placeholder="请输入印面尺寸" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="印文排列" prop="textArrangement">
                <el-input v-model="formData.textArrangement" placeholder="请输入印文排列" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="印文内容" prop="sealContent">
                <Editor v-model="formData.sealContent" height="150px" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="藏品附件" name="3">
          <el-row :gutter="20">
            <!-- 0：藏品主图 -->
            <el-col :span="24">
              <el-form-item label="藏品主图" prop="collectionCover">
                <UploadImg
                  style="margin-left: 50px"
                  v-model="formData.collectionCover"
                  :fileSize="200"
                  :fileType="['jpeg', 'jpg', 'png', 'gif', 'webp']"
                  height="120px"
                  width="120px"
                  @change="(files) => handleFileChange(files, 'images')"
                  :isShowTip="true"
                />
              </el-form-item>
            </el-col>

            <!-- 1：藏品图片 -->
            <el-col :span="24">
              <el-form-item label="藏品图片" prop="collectionImages">
                <UploadImgs
                  style="margin-left: 50px"
                  v-model="collectionImages"
                  :limit="20"
                  :fileSize="200"
                  :fileType="['jpeg', 'jpg', 'png', 'gif', 'webp']"
                  height="120px"
                  width="120px"
                  @change="(files) => handleFileChange(files, 'images')"
                  :isShowTip="true"
                  :fileNames="Object.fromEntries(fileNameMaps.images)"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="藏品音频" prop="collectionAudios">
                <div style="margin-left: 50px">
                  <UploadFile
                    v-model="collectionAudios"
                    :limit="5"
                    :fileSize="500"
                    :fileType="['mp3', 'wav', 'ogg', 'aac', 'm4a', 'flac']"
                    @change="(files) => handleFileChange(files, 'audios')"
                    :fileNames="Object.fromEntries(fileNameMaps.audios)"
                  />
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="藏品视频" prop="collectionVideos">
                <div style="margin-left: 50px">
                  <UploadFile
                    v-model="collectionVideos"
                    :limit="3"
                    :fileSize="500"
                    :fileType="['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv']"
                    @change="(files) => handleFileChange(files, 'videos')"
                    :fileNames="Object.fromEntries(fileNameMaps.videos)"
                  />
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="藏品三维文件" prop="collection3DFiles">
                <div style="margin-left: 50px">
                  <UploadFile
                    v-model="collection3DFiles"
                    :limit="5"
                    :fileSize="500"
                    :fileType="['obj', 'glb']"
                    @change="(files) => handleFileChange(files, 'files3D')"
                    :fileNames="Object.fromEntries(fileNameMaps.files3D)"
                  />
                </div>
              </el-form-item>
            </el-col>

            <!-- 5：链接地址 -->
            <el-col :span="24">
              <el-form-item label="链接地址" prop="collectionLinks">
                <div class="link-input-container" style="margin-left: 50px">
                  <div
                    v-for="(link, index) in collectionLinks"
                    :key="index"
                    class="link-input-item"
                  >
                    <el-input v-model="link.url" placeholder="请输入链接地址" clearable>
                      <template #prepend>链接{{ index + 1 }}</template>
                      <template #append>
                        <el-button
                          @click="removeLink(index)"
                          type="danger"
                          size="small"
                          v-if="collectionLinks.length > 1"
                        >
                          <Icon icon="ep:delete" />
                        </el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-button @click="addLink" type="primary" size="small" class="add-link-btn">
                    <Icon icon="ep:plus" /> 添加链接
                  </el-button>
                </div>
                <div class="upload-tip" style="margin-left: 50px">可添加多个相关链接地址</div>
              </el-form-item>
            </el-col>

            <!-- 6：藏品精准三维文件 -->
            <el-col :span="24">
              <el-form-item label="藏品精准三维文件" prop="collection3DPreciseFiles">
                <div style="margin-left: 50px">
                  <UploadFile
                    v-model="collection3DPreciseFiles"
                    :limit="3"
                    :fileSize="2000"
                    :fileType="['obj', 'glb', 'gltf', 'fbx', 'dae', 'ply', 'stl', '3ds']"
                    @change="(files) => handleFileChange(files, 'preciseFiles3D')"
                    :fileNames="Object.fromEntries(fileNameMaps.preciseFiles3D)"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane name="4" :disabled="!formData.id">
          <template #label>
            <el-tooltip
              effect="dark"
              content="请先保存基本信息"
              placement="top-start"
              :disabled="!!formData.id"
            >
              <span>二维采集信息</span>
            </el-tooltip>
          </template>
          <collectionimageacquisition :data="formData" />
        </el-tab-pane>
        <el-tab-pane name="5" :disabled="!formData.id">
          <template #label>
            <el-tooltip
              effect="dark"
              content="请先保存基本信息"
              placement="top-start"
              :disabled="!!formData.id"
            >
              <span>三维采集信息</span>
            </el-tooltip>
          </template>
          <collection3dacquisition :data="formData" />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
      <el-button @click="closeForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { defaultPropsTree, handleTree } from '@/utils/tree'
import { CollectionManagementApi, CollectionManagementVO } from '@/api/dr/collectionmanagement'
import { getDictDataByParentId } from '@/api/system/dict/dict.data'
import collectionimageacquisition from '../collectionimageacquisition/index.vue'
import collection3dacquisition from '../collection3dacquisition/index.vue'

/** 藏品管理 表单 */
defineOptions({ name: 'CollectionManagementForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeTab = ref('1') // 活动的标签页
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  collectionLinkAddress: [] // 统一存储所有多媒体文件和链接
})
// 多媒体文件数据
const collectionImages = ref<string>('') // 藏品图片
const collectionAudios = ref<string>('') // 藏品音频
const collectionVideos = ref<string>('') // 藏品视频
const collection3DFiles = ref<string>('') // 藏品三维文件
const collection3DPreciseFiles = ref<string>('') // 藏品精准三维文件

// 文件名映射 - 存储URL到原始文件名的映射关系
const fileNameMaps = ref({
  images: new Map<string, string>(),
  audios: new Map<string, string>(),
  videos: new Map<string, string>(),
  files3D: new Map<string, string>(),
  preciseFiles3D: new Map<string, string>()
})
// 链接地址数据
const collectionLinks = ref([{ url: '' }]) // 初始化一个空链接

const formRules = reactive({
  generalAccessionNumber: [{ required: true, message: '总登记号不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '类别不能为空', trigger: 'change' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  originalName: [{ required: true, message: '原名不能为空', trigger: 'blur' }],
  coverImage: [{ required: true, message: '封面图片路径不能为空', trigger: 'blur' }],
  materialType: [{ required: true, message: '质地类别不能为空', trigger: 'change' }],
  actureQuantity: [{ required: true, message: '实际数量不能为空', trigger: 'blur' }],
  quality: [{ required: true, message: '质量不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '件数(套)不能为空', trigger: 'blur' }],
  grade: [{ required: true, message: '级别不能为空', trigger: 'change' }],
  source: [{ required: true, message: '来源不能为空', trigger: 'change' }],
  conditionStatus: [{ required: true, message: '完残状况不能为空', trigger: 'change' }],
  preservationStatus: [{ required: true, message: '保存状态不能为空', trigger: 'change' }],
  entryDate: [{ required: true, message: '入馆日期不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  getDictData()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CollectionManagementApi.getCollectionManagement(id)
      const materialCategory3: number[] = []
      if (formData.value.materialCategory1)
        materialCategory3.push(+formData.value.materialCategory1)
      if (formData.value.materialCategory2)
        materialCategory3.push(+formData.value.materialCategory2)
      if (formData.value.material) materialCategory3.push(+formData.value.material)
      materialCategory3.filter((val) => val || val === 0)
      formData.value.materialCategory3 = materialCategory3

      const eras: number[] = []
      if (formData.value.chineseHistoricalEra) eras.push(+formData.value.chineseHistoricalEra)
      if (formData.value.archaeologicalEra) eras.push(+formData.value.archaeologicalEra)
      if (formData.value.geologicalEra) eras.push(+formData.value.geologicalEra)
      if (formData.value.era) eras.push(+formData.value.era)
      formData.value.eras = eras

      // 获取多媒体文件数据
      loadCollectionMediaFiles(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const cataList = ref<any[]>([])
const eraList = ref<any[]>([])
const getDictData = () => {
  getDictDataByParentId({ parentId: 1 }).then((res) => {
    console.log('getDictDataByParentId res', res)
    cataList.value = handleTree(res)
  })
  getDictDataByParentId({ parentId: 1901 }).then((res) => {
    console.log('getDictDataByParentId res', res)
    eraList.value = handleTree(res)
  })
}
// materialCategory1, materialCategory2, materialCategory3=material
const onChangeMaterial = (values) => {
  console.log('onChangeMaterial values', values)
  formData.value.materialCategory1 = values[0]
  formData.value.materialCategory2 = values[1]
  formData.value.material = values[2]
}
// chineseHistoricalEra,archaeologicalEra,geologicalEra,era
const onChangeEras = (values) => {
  console.log('onChangeEras values', values)
  formData.value.chineseHistoricalEra = values[0]
  formData.value.archaeologicalEra = values[1]
  formData.value.geologicalEra = values[2]
  formData.value.era = values[3]
}
// 文件名处理函数
const handleFileChange = (
  files: any[],
  type: 'images' | 'audios' | 'videos' | 'files3D' | 'preciseFiles3D'
) => {
  console.log(`📁 ${type} 文件变化:`, files)
  const fileList = Array.isArray(files) ? files : []

  // 清空旧的映射
  fileNameMaps.value[type].clear()

  // 建立新的URL到文件名映射
  fileList?.forEach((file) => {
    if (file.url && file.name) {
      fileNameMaps.value[type].set(file.url, file.name)
      console.log(`💾 保存文件名映射: ${file.url} -> ${file.name}`)
    }
  })
}
// 链接地址操作函数
const addLink = () => {
  collectionLinks.value.push({ url: '' })
}

const removeLink = (index: number) => {
  if (collectionLinks.value.length > 1) {
    collectionLinks.value.splice(index, 1)
  }
}
// 将各个文件变量转换为统一的collectionLinkAddress数组
const buildCollectionLinkAddress = () => {
  const linkAddresses: any[] = []

  // 0: 藏品主图
  if (formData.value.collectionCover) {
    linkAddresses.push({
      type: 0,
      linkAddress: formData.value.collectionCover,
      fileName: formData.value.collectionCover.substring(
        formData.value.collectionCover.lastIndexOf('/') + 1
      ) // 主图从URL提取文件名
    })
  }

  // 1: 藏品图片 (多个)
  if (collectionImages.value) {
    const images = collectionImages.value.split(',').filter((url) => url.trim())
    images.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 1,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.images.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 2: 藏品音频 (多个)
  if (collectionAudios.value) {
    const audios = collectionAudios.value.split(',').filter((url) => url.trim())
    audios.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 2,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.audios.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 3: 藏品视频 (多个)
  if (collectionVideos.value) {
    const videos = collectionVideos.value.split(',').filter((url) => url.trim())
    videos.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 3,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.videos.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 4: 藏品三维文件 (多个)
  if (collection3DFiles.value) {
    const files3D = collection3DFiles.value.split(',').filter((url) => url.trim())
    files3D.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 4,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.files3D.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 5: 链接地址 (多个)
  collectionLinks.value.forEach((link) => {
    if (link.url && link.url.trim()) {
      linkAddresses.push({
        type: 5,
        linkAddress: link.url.trim(),
        fileName: link.url.trim() // 链接地址使用URL本身作为显示名称
      })
    }
  })

  // 6: 藏品精准三维文件 (多个)
  if (collection3DPreciseFiles.value) {
    const preciseFiles3D = collection3DPreciseFiles.value.split(',').filter((url) => url.trim())
    preciseFiles3D.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 6,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.preciseFiles3D.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  formData.value.collectionLinkAddress = linkAddresses
  console.log('🔗 构建的collectionLinkAddress（包含fileName）：', linkAddresses)
}

// 加载藏品多媒体文件数据
const loadCollectionMediaFiles = async (collectionId: number) => {
  try {
    const linkData = await CollectionManagementApi.getCollectionModelLinkAddress({
      collectionId,
      bizType: 1
    })
    console.log('🔗 获取的多媒体数据：', linkData)

    if (linkData && Array.isArray(linkData)) {
      // 清空文件名映射
      Object.keys(fileNameMaps.value).forEach((key) => {
        fileNameMaps.value[key as keyof typeof fileNameMaps.value].clear()
      })

      // 解析返回的数据到各个变量
      const images: string[] = []
      const audios: string[] = []
      const videos: string[] = []
      const files3D: string[] = []
      const preciseFiles3D: string[] = []
      const links: any[] = []

      linkData.forEach((item: any) => {
        console.log(item, 'item')
        // 将type转换为数字进行比较
        const typeNum = parseInt(item.type)
        const url = item.linkAddress
        const fileName = item.fileName || url.substring(url.lastIndexOf('/') + 1)
        console.log('fileName', fileName)

        switch (typeNum) {
          case 0: // 藏品主图
            formData.value.collectionCover = url
            break
          case 1: // 藏品图片
            images.push(url)
            fileNameMaps.value.images.set(url, fileName)
            break
          case 2: // 藏品音频
            audios.push(url)
            fileNameMaps.value.audios.set(url, fileName)
            break
          case 3: // 藏品视频
            videos.push(url)
            fileNameMaps.value.videos.set(url, fileName)
            break
          case 4: // 藏品三维文件
            files3D.push(url)
            fileNameMaps.value.files3D.set(url, fileName)
            break
          case 5: // 链接地址
            links.push({ url: url })
            break
          case 6: // 藏品精准三维文件
            preciseFiles3D.push(url)
            fileNameMaps.value.preciseFiles3D.set(url, fileName)
            break
        }
      })

      // 更新各个ref变量
      collectionImages.value = images.join(',')
      collectionAudios.value = audios.join(',')
      collectionVideos.value = videos.join(',')
      collection3DFiles.value = files3D.join(',')
      collection3DPreciseFiles.value = preciseFiles3D.join(',')
      collectionLinks.value = links.length > 0 ? links : [{ url: '' }]

      console.log('📂 设置的多媒体文件（包含文件名映射）：', {
        cover: formData.value.collectionCover,
        images: collectionImages.value,
        audios: collectionAudios.value,
        videos: collectionVideos.value,
        files3D: collection3DFiles.value,
        preciseFiles3D: collection3DPreciseFiles.value,
        links: collectionLinks.value,
        fileNameMaps: {
          images: Array.from(fileNameMaps.value.images.entries()),
          audios: Array.from(fileNameMaps.value.audios.entries()),
          videos: Array.from(fileNameMaps.value.videos.entries()),
          files3D: Array.from(fileNameMaps.value.files3D.entries()),
          preciseFiles3D: Array.from(fileNameMaps.value.preciseFiles3D.entries())
        }
      })
    }
  } catch (error) {
    console.error('获取多媒体文件失败：', error)
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  const validate = await formRef.value.validate().catch(() => false)
  if (!validate) {
    message.error('请检查表单信息，确保所有必填项都已正确填写')
    return
  }
  // 提交请求
  formLoading.value = true
  // 提交前构建collectionLinkAddress数组
  buildCollectionLinkAddress()

  try {
    const data = formData.value as unknown as CollectionManagementVO
    if (!data.id) {
      const res = await CollectionManagementApi.createCollectionManagement(data)
      console.log('createCollectionManagement res', res)
      message.success(t('common.actionSuccess'))
      formData.value.id = res.id
    } else {
      await CollectionManagementApi.updateCollectionManagement(data)
      message.success(t('common.actionSuccess'))
    }
    // 保存成功后刷新列表数据
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const closeForm = () => {
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    collectionLinkAddress: [] // 初始化为空数组
  }
  // 重置多媒体文件数据
  collectionImages.value = ''
  collectionAudios.value = ''
  collectionVideos.value = ''
  collection3DFiles.value = ''
  collection3DPreciseFiles.value = ''
  // 重置文件名映射
  Object.keys(fileNameMaps.value).forEach((key) => {
    fileNameMaps.value[key as keyof typeof fileNameMaps.value].clear()
  })
  // 重置链接数据
  collectionLinks.value = [{ url: '' }]
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
  margin-left: 10px;
}

/* 为每个上传区域增加间距 */
:deep(.el-form-item) {
  margin-bottom: 24px;
}

/* 上传组件样式优化 */
:deep(.upload-file-uploader) {
  margin-bottom: 8px;
}

/* 图片上传网格布局优化 */
:deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 链接输入框样式 */
.link-input-container {
  width: 100%;
  .link-input-item {
    margin-bottom: 12px;
  }

  .link-input-item:last-child {
    margin-bottom: 0;
  }

  .add-link-btn {
    margin-top: 8px;
  }
}
</style>
